﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace TestServer {
    class Server {
        private TcpListener tcpListener;
        private Thread listenThread;
        private IPAddress ServerIPAddress;
        private int ServerConnectionPort;

        public Server(IPAddress IPAddr, int Port) {
            this.tcpListener = new TcpListener(IPAddress.Any, Port);
            this.ServerIPAddress = IPAddr;
            this.ServerConnectionPort = Port;
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }

        private void ListenForClients() {
            this.tcpListener.Start();

            GameServer server = new GameServer();

            string ServerDetails = ServerIPAddress.ToString() + ":" + ServerConnectionPort.ToString();
            server.RegisterServer(ServerDetails);

            Console.WriteLine("Listening on " + ServerDetails);
            while (true) {
                //Console.WriteLine("Listening ...");
                //blocks until a client has connected to the server
                TcpClient client = this.tcpListener.AcceptTcpClient();

                Console.WriteLine("---------------------------------\n" + client.Client.LocalEndPoint.ToString() + " connected...\n---------------------------------");

                GameClient gameClient = new GameClient(server, client);
                server.RegisterClient(gameClient);
            }
        }
    }
}
